package com.caishi.lkx.user.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caishi.lkx.common.AclResultCode;
import com.caishi.lkx.common.BaseApi;
import com.caishi.lkx.common.ienum.DeviceType;
import com.caishi.lkx.common.ienum.PlatformType;
import com.caishi.lkx.common.role.Role;
import com.caishi.lkx.common.role.Roles;
import com.caishi.lkx.user.dto.UserRecordsVo;
import com.caishi.lkx.user.ienum.type.*;
import com.caishi.lkx.user.model.*;
import com.caishi.lkx.user.service.*;
import com.caishi.lkx.user.service.impl.UserServiceImpl;
import com.caishi.lkx.user.vo.SimpleUserVo;
import com.caishi.lkx.user.vo.UserAllDataVo;
import com.zzw.common.Fetch;
import com.zzw.common.Wrappers;
import com.zzw.common.exception.BizRuntimeException;
import com.zzw.common.utils.CommonUtil;

import com.caishi.lkx.common.VipsmartAesUtil;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Function;

/**
 * @author by keray
 * date:2021/4/13 4:56 下午
 */
@RestController
@RequestMapping("/user/cu/user")
@Tag(name = "用户相关")
@Slf4j
public class UserApi extends BaseApi {
    @Resource
    private UserServiceImpl userService;

    @Resource
    private IAdminUserService adminUserService;

    @Resource
    private IMemberService memberService;

    @Resource
    private IGroupService groupService;

    @Resource
    private ILoginInfoService loginInfoService;
    @Resource
    private ISysHelpService sysHelpService;


    @GetMapping("/page")
    @Roles(Role.admin)
    public IPage<UserModel> page(@ModelAttribute Page<UserModel> page, @ModelAttribute UserModel model) {
        return userService.page(page, Wrappers.<UserModel>lambdaQuery().like(StrUtil.isNotBlank(model.getName()), UserModel::getName, model.getName())
                .apply(model.getUserType() != null, " user_type & {0} = {1}", model.getUserType(), model.getUserType())
        );
    }

    @Operation(summary = "获取当前用户", description = "用户类型为学生时返回学号， 老师时返回教工号")
    @GetMapping("/current")
    public Object currentUser(HttpServletRequest request) {
        tokenV();
        DeviceType deviceType = userContext.currentTokenData().getDevice();
        String userId = userContext.currentUserId();
        UserModel m = userService.getUserDetail(userId);
        //userService.updateHaveType(userContext.currentPlatform().convertHaveType(), m);
        if (deviceType == DeviceType.admin) {
            IUserModel<?> res = m;
            if (UserType.intHaveType(m.getUserType(), UserType.admin)) {
                res = adminUserService.adminUserDetail(m.getId());
            }
            res.setMobile(CommonUtil.mobileSafe(m.getMobile()));
            return res;
        }
        UserAllDataVo userAllDataVo = new UserAllDataVo();
        if (m.getHaveType() == null) {
            m.addHaveType(HaveType.vers7);
        }
        HaveType[] haveTypes = HaveType.int2Array(m.getHaveType());
        userAllDataVo.setHaveTypes(haveTypes);

        userAllDataVo.setEncryptMobile(VipsmartAesUtil.encryptStr(userAllDataVo.getMobile()));
        userAllDataVo.setEncryptId(VipsmartAesUtil.encryptStr(userAllDataVo.getId()));
        userAllDataVo.setMobile(CommonUtil.mobileSafe(userAllDataVo.getMobile()));
        // 设置机构绑定信息
//        if (userAllDataVo.getGroupId() != null && userAllDataVo.getGroupId() > 0) {
//            var msg = groupService.userBindGroupMessage(userAllDataVo.getGroupId());
//            if (msg != null) {
//                userAllDataVo.setGroupMessage(msg);
//                userAllDataVo.setGroupCode(msg.getGroupCode());
//                if (UserType.intHaveType(m.getUserType(), UserType.groupAdmin)) {
//                    if (null != msg.getExpireDate()) {
//                        userAllDataVo.setMemberExpireDate(msg.getExpireDate().atTime(23, 59, 59));
//                    }
//                }
//            }
//        }
        String username = userAllDataVo.getMobile();
        LoginInfoModel loginInfoModel = loginInfoService.selectUserLoginInfo(userId, UserAccountType.group);
        if (null != loginInfoModel) {
            username = loginInfoModel.getAccount();
        }
        if (loginInfoModel == null) {
            loginInfoModel = loginInfoService.selectUserLoginInfo(userId, UserAccountType.username);
            if (loginInfoModel != null) {
                username = loginInfoModel.getAccount();
            }
        }
        userAllDataVo.setUsername(username);
        userAllDataVo.setName(m.getName());
        return userAllDataVo;
    }

    private void convertMemberVo(HttpServletRequest request, String userId, UserModel m, UserAllDataVo userAllDataVo) {
        MemberModel memberModel = memberService.getUserDetail(userId, m);
        //判断是否carsi用户
        if (UserChannelType.carsi.equals(memberModel.getChannelType())) {
            userAllDataVo.setIsCarsi(true);
        } else {
            userAllDataVo.setIsCarsi(false);
        }
        PlatformType platformType = userContext.currentPlatform();
        if (platformType.equals(PlatformType.KAOYAN)) {
            //第一次登录的到考研平台
            if (null == memberModel.getKaoyanExpireTime() && null != memberModel.getGroupId()) {
//                LocalDate userExpireTime = groupService.getUserExpireTime(groupService.getById(memberModel.getGroupId()), platformType);
//                if (null != userExpireTime) {
//                    memberModel.setKaoyanExpireTime(userExpireTime.atTime(23, 59, 59));
//                }
//                memberService.update(memberModel);
//                if (null == userExpireTime) {
//                    memberModel.setUserType(UserType.member.getValue());
//                    memberModel.setGroupId(null);
//                }
                try {
//                    RegisterUserLogDto logDto = RegisterUserLogDto.builder()
//                            .userId(userId)
//                            .groupId(memberModel.getGroupId())
//                            .sourceType(request.getHeader("platform"))
//                            .ip(userContext.currentIp())
//                            .count(1)
//                            .image(MapUtil.<String, Object>builder()
//                                    .put("gid", GroupFilter.getGid(request))
//                                    .put("ua", request.getHeader("User-Agent"))
//                                    .put("path", request.getHeader("Referer")).build()).build();
//                    rocketMQTemplate.sendOneWay("registerUserLog", logDto);
                } catch (Exception e) {
                    log.error("日志发送mq失败:{}", e);
                }

            }
            userAllDataVo.setMemberExpireDate(memberModel.getKaoyanExpireTime());
        } else {
            LocalDateTime expireTime = memberModel.getExpireTime();
            if (null == expireTime && null != memberModel.getGroupId()) {
//                LocalDate userExpireTime = groupService.getUserExpireTime(groupService.getById(memberModel.getGroupId()), platformType);
//                if (null != userExpireTime) {
//                    expireTime = userExpireTime.atTime(23, 59, 59);
//                }
                memberModel.setExpireTime(expireTime);
                memberService.update(memberModel);
//                if (null == userExpireTime) {
//                    memberModel.setUserType(UserType.member.getValue());
//                    memberModel.setGroupId(null);
//                }
            }
            userAllDataVo.setMemberExpireDate(expireTime);
        }
        //存在用户有机构管理员类型 但不是机构管理员 如(云课堂机构管理员)
        UserType[] userTypes = memberModel.getUserTypes();

        userAllDataVo.setUserTypes(memberModel.getUserTypes());
        BeanUtil.copyProperties(memberModel, userAllDataVo);
    }

    @GetMapping("/token-v")
    public void tokenV() {
        String userId = userContext.currentUserId();
        String uuid = userContext.currentTokenData().getDeviceUUID();
        DeviceType deviceType = userContext.currentTokenData().getDevice();
        if (userService.userVersionIsOver(userId, deviceType, uuid)) {
            throw new BizRuntimeException(AclResultCode.busyLine);
        }
    }


    @Operation(summary = "修改用户基础信息")
    @PutMapping("/base-update")
    public UserModel update(@RequestParam String id,
                            String header,
                            String name,
                            Sex sex
    ) {
        UserModel model = new UserModel();
        model.setId(userContext.currentUserId());
        model.setHeader(header);
        model.setName(name);
        model.setSex(sex);
        return userService.simpleUpdate(model);
    }


    @Operation(summary = "获取当前用户手机号")
    @GetMapping("/current-mobile")
    public String currentMobile() {
        return Fetch.fetch(userService.selectOne(
                Wrappers.<UserModel>lambdaQuery()
                        .select(UserModel::getMobile)
                        .eq(UserModel::getId, userContext.currentUserId())
        )).then((Function<UserModel, String>) IUserModel::getMobile).catchFetch((e, catchFetch) -> null).getData();
    }

    @Operation(summary = "修改用户状态")
    @Parameters({
            @Parameter(name = "status", description = "修改状态 true 启用 false禁用", required = true),
            @Parameter(name = "id", description = "用户id", required = true),
    })
    @PostMapping("/enable/{status}/{id}")
    @Roles({Role.admin})
    public void settingEnable(@PathVariable String id, @PathVariable Boolean status) {
        userService.lockUser(status, id);
        userService.updateUserLoginVersion(id);
    }

    @Operation(summary = "用户简单信息", description = "仅返回id，名字，头像，性别")
    @Parameters({
            @Parameter(name = "id", description = "用户id", required = true),
    })
    @GetMapping("/detail/{id}")
    @Roles({Role.admin})
    public UserModel userInfo(@PathVariable String id) {
        var r = userService.getUserDetail(id);
        if (null == r) {
            return null;
        }
        r.setMobile(CommonUtil.mobileSafe(r.getMobile()));
        return r;
    }


    /**
     * ========================================================不需要登录接口===================================================================================
     */

    @Operation(summary = "用户简单信息", description = "仅返回id，名字，头像，性别")
    @Parameters({
            @Parameter(name = "id", description = "用户id", required = true),
    })
    @GetMapping("/detail/simple/{id}")
    @Roles
    public SimpleUserVo userSimpleInfo(@PathVariable String id) {
        return userService.userSimpleMsg(id);
    }

    @Operation(summary = "学情数据")
    @Parameters({
            @Parameter(name = "categoryId", description = "科目id", required = true),
    })
    @GetMapping("/current-records/{categoryId}")
    public UserRecordsVo userRecords(@PathVariable Long categoryId) {
        if (null == categoryId) {
            throw new BizRuntimeException();
        }
        return memberService.getUserRecordsByCategoryId(categoryId, userContext.currentUserId());
    }
    /**
     * 根据类型获取树状结构数据
     * */
    @GetMapping("/help/{type}")
    public List<HelpModel> getTreeData(@PathVariable("type") String type){
        return sysHelpService.getTreeDataByType(type);
    }
}
